/**
 * 
 * @class ActivityASyncJsonHttpRequestBase
 * @fuction Async Acccess HttpService Base, callback is called within mainUI Thread
 *
 */
package me.weijing.common.http;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

import me.weijing.common.AppManager;

import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public abstract class ActivityASyncJsonHttpRequestBase extends AsyncHttpRequestBase {
    public ActivityASyncJsonHttpRequestBase(Context context) {
        super(context);
        mCallback = new HttpProgressCallbackImpl();
    }

    public abstract void processResult(JSONObject json);

    public abstract void processFailed(EFailType failtype, int resultCode, String errMsg, JSONObject data);

    @Override
    public void cancel() {
        ((HttpProgressCallbackImpl) mCallback).setCanceled(true);
        super.cancel();
    }

    public void aGet(RequestParams reqParam) {

        try {
            String realurl = buildUrl(reqParam);
            Log.i("TAG", realurl);
            mThreadPool.execute(new HttpRequestGet(getUrl(), realurl, mCallback, gExtraHeader));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_CLIENT_CREATETHREAD, null, null);
                processFinish();
            } catch (Exception e2) {
                e2.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    public void aPost(RequestParams reqParam) {

        try {
            String realurl = buildUrl(null);
            Log.i("TAG", realurl);
            mThreadPool.execute(new HttpRequestPost(getUrl(), realurl, mCallback, gExtraHeader, reqParam));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_CLIENT_CREATETHREAD, null, null);
                processFinish();
            } catch (Exception e2) {
                e2.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    public void aPost(JSONObject jsonParam) {
        try {
            String realurl = buildUrl(null);
            mThreadPool.execute(new HttpRequestJsonPost(getUrl(), realurl, mCallback, gExtraHeader, jsonParam));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_CLIENT_CREATETHREAD, null, null);
                processFinish();
            } catch (Exception e2) {
                e2.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    public void aPostFile(String filePath, String fileName, Map<String, String> extraParam) {

        try {
            String realurl = buildUrl(null);
            String key = "uploadfile";
            RequestParams reqParam = new RequestParams(extraParam);
            reqParam.put(key, new FileInputStream(new File(filePath)), fileName);
            mThreadPool.execute(new HttpRequestPost(getUrl(), realurl, mCallback, gExtraHeader, reqParam));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_CLIENT_CREATETHREAD, null, null);
                processFinish();
            } catch (Exception e2) {
                e2.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    class HttpProgressCallbackImpl implements HttpProgressCallback {
        private boolean bCanceled = false;

        public void setCanceled(boolean bCancel) {
            this.bCanceled = bCancel;
        }

        @Override
        public boolean isCanceled() {
            return bCanceled;
        }

        @Override
        public void startProgress() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (checkSessionTag() == false)
                            return;
                        launchProgress();

                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void progressPublish(final int progress) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (checkSessionTag() == false)
                            return;
                        publishProgress(progress);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });
        }

        /**
         * 返回的请求数
         * 
         * @param data
         *            为null表示请求失败
         */
        @Override
        public void interpret(byte[] data) {
            String errMsg = "connect fail";
            JSONObject jsonObj1 = null;
            int errcode = FAILTYPE_NETFAIL;
            if (null != data) {
                try {
                    jsonObj1 = new JSONObject(new String(data, "UTF-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                    errMsg = "not validate json";
                    data = null;
                    errcode = FAILTYPE_SERVER_FAIL;
                }
            }

            if (null == data) {
                final String msg = errMsg;
                final int httperrcode = errcode;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (checkSessionTag() == false)
                                return;
                            processFailed(EFailType.EFAILTYPE_SYS, httperrcode, msg, null);

                        } catch (Exception e) {
                            e.printStackTrace();
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                        try {
                            processFinish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                    }
                });
            } else {

                final JSONObject jsonObj = jsonObj1;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!checkSessionTag())
                            return;
                        try {
                            if (AppManager.isActivityDestroyed(mContext)) {
                                // processFailed(EFailType.EFAILTYPE_APP,0,
                                // "",jsonObj);
                                // fix when net
                            } else {
                                processResult(jsonObj);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                        try {
                            processFinish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                    }
                });
            }
        }

        @Override
        public void serverFail(final int httpCode) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (checkSessionTag() == false)
                        return;
                    try {
                        processFailed(EFailType.EFAILTYPE_APP, httpCode, null, null);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                    try {
                        processFinish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });

        }

        @Override
        public void interpret(byte[] data, Map<String, List<String>> responseHeaders) {
            interpret(data);
        }
    }
}
